package com.example.a828502.callsystemcamera;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private Button btnTakePhoto,btnSelectPicture;
    private ImageView imgShow;
    private static final int CAMERA = 100;
    private static final int PICTURE = 101;
    private static final int PHOTO_REQUEST_CUT = 103;//裁剪图片
    private File cameraFile ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imgShow = (ImageView)findViewById(R.id.imgShow);
        btnTakePhoto = (Button)findViewById(R.id.TakePhotoBtn);
        btnSelectPicture = (Button)findViewById(R.id.SelectPictureBtn);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                startActivityForResult(camera, CAMERA);

                //调用相机拍照的时候，设定好保存路径
                File sdcardDir = Environment .getExternalStorageDirectory();
                new DateFormat();
                String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + "test.jpg";
                String filename = null;
                try {
                    filename = sdcardDir.getCanonicalPath()+ "/DCIM/Camera/"  +name;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                cameraFile = new File(filename);

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                startActivityForResult(intent, CAMERA);


            }
        });
        btnSelectPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentFromGallery = new Intent(Intent.ACTION_GET_CONTENT);
                intentFromGallery.addCategory(Intent.CATEGORY_OPENABLE);
                intentFromGallery.setType("image/jpeg");
                startActivityForResult(intentFromGallery, PICTURE);
            }
        });
    }

    @Override
    protected void  onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case CAMERA:
                if (resultCode == RESULT_OK){
                    String sdStatus = Environment.getExternalStorageState();
                    if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
                        Log.i("TestFile",
                                "SD card is not avaiable/writeable right now.");
                        return;
                    }
//                    try {
//                        FileInputStream fis = new FileInputStream(cameraFile);
//                        Bitmap bimap = BitmapFactory.decodeStream(fis);
//                        imgShow.setImageBitmap(bimap);
//                            Toast.makeText(this,"拍摄照片成功",Toast.LENGTH_LONG).show();
//                        }
//                        catch (FileNotFoundException e)
//                        {
//                            e.printStackTrace();
//                        }
//                        catch (IOException e)   {
//                            e.printStackTrace();
//                        }
                    startPhotoZoom(Uri.fromFile(cameraFile));
                }
                break;
            case PICTURE:
                if (resultCode == RESULT_OK){
////                    String path = SelectPicUtil.getPath(this, data.getData());
////                    Bitmap compressedBitmap = ImageUtils.getCompressedBitmap(path, 450, 300);
//                    Uri selectedImage = data.getData();
//                    String[] filePathColumns={MediaStore.Images.Media.DATA};
//                    Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,null, null);
//                    c.moveToFirst();
//                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
//                    String picturePath= c.getString(columnIndex);
//                    c.close();
//                    imgShow.setImageURI(selectedImage);

                    startPhotoZoom(data.getData());

                }
                break;
            case PHOTO_REQUEST_CUT:// 返回的结果
                if (data != null)
                {
                    Bitmap photo1 = data.getParcelableExtra("data");
                    imgShow.setImageBitmap(photo1);
                }
                break;
        }
    }

    /**
     * 裁剪图片
     * @param uri
     */

    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        System.out.println("22================");
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }
}
